package com.redstar.HappyRefresh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redstar.HappyRefresh.mapper.VideoStarMapper;
import com.redstar.HappyRefresh.pojo.VideoStar;
import com.redstar.HappyRefresh.service.VideoStarService;
import org.springframework.stereotype.Service;

@Service
public class VideoStarServiceImpl extends ServiceImpl<VideoStarMapper, VideoStar> implements VideoStarService {
    @Override
    public Boolean starState(Long videoId, Long userId) { // userId是否点赞videoId
        if (userId == null) { // 游客登录
            return false;
        }
        long count = count(new LambdaQueryWrapper<VideoStar>().eq(VideoStar::getUserId, userId).eq(VideoStar::getVideoId, videoId));
        return count == 1;
    }

    @Override
    public Boolean starVideo(VideoStar videoStar) { // 点赞视频/取消点赞
        try { // 点赞
            // videoId和userId是VideoStar表的唯一索引，重复插入会抛出异常，表示取消点赞
            save(videoStar);
        } catch (Exception e) { // 取消点赞
            Long videoId = videoStar.getVideoId();
            Long userId = videoStar.getUserId();
            remove(new LambdaQueryWrapper<VideoStar>().eq(VideoStar::getUserId, userId).eq(VideoStar::getVideoId, videoId));
            return false;
        }
        return true;
    }
}
